import java.sql.*;

public class MyDb {
    private Connection conn = null;
    private Statement st = null;
    private ResultSet rs = null;
    private PreparedStatement pst = null;

    public MyDb(String dbname, String username, String password) {
        try {
            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/";
            url += dbname + "?characterEncoding=utf8&useSSL=true";

            conn = DriverManager.getConnection(url, username, password);

            st = conn.createStatement(
                    ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int query(String sql) {
        int row = 0;
        try {
            rs = st.executeQuery(sql);
            rs.last();
            row = rs.getRow();
            rs.absolute(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    public MyDb preSql(String sql) {
        try {
            pst = conn.prepareStatement(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public MyDb preSet(int index, String data) {
        try {
            pst.setString(index, data);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return this;
    }

    public int preExec() {
        int row = 0;
        try {
            rs = pst.executeQuery();
            rs.last();
            row = rs.getRow();
            rs.absolute(0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return row;
    }

    public ResultSet getResult() {
        return rs;
    }

    public Connection getConnection() {
        return conn;
    }

    public Statement getStmt() {
        return st;
    }

    public PreparedStatement getPreStmt() {
        return pst;
    }

    public void close() {
        try {
            if (rs != null)
                rs.close();
            if (pst != null)
                pst.close();
            if (st != null)
                st.close();
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
